package com.frxuexi.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.SPUtils
import com.frxuexi.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception
import java.lang.RuntimeException
import java.text.SimpleDateFormat

open class BaseViewModel:ViewModel() {
//    by lazy：1.延迟初始化，2.只获取一次对象
    val onFailed by lazy { MutableLiveData<Throwable>() }

    fun <T> roomRequest(s:()->T,
                    success:(T)->Unit,
                    failed:(Throwable)->Unit=onFailed::postValue){
        viewModelScope.launch {
            try {
                val res = s.invoke()//调用dao里的接口
                if(res!=null){
//                    Log.i("===",res.toString())
                    success(res)
                }else{
                    failed(RuntimeException("操作失败"))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }

    fun <T> httpRequest(s:suspend ()->Res<T>,
                    success:(T)->Unit,
                    failed:(Throwable)->Unit=onFailed::postValue){
        viewModelScope.launch {
            try {
                val res = s.invoke()//调用apiService里的接口
                if(res.code==200){
                    success(res.data)
                }else{
                    failed(RuntimeException(res.message))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }

    /*fun <T> httpRequestHourse(s:suspend ()->ResHourse<T>,
                            success:(T)->Unit,
                            failed:(Throwable)->Unit=onFailed::postValue){
        viewModelScope.launch {
            try {
                val res = s.invoke()//调用apiService里的接口
                if(res.status=="C0000"){
                    success(res.result)
                }else{
                    failed(RuntimeException(res.message))
                }
            }catch (e:Exception){
                failed(e)
            }
        }
    }*/

    fun mapToBody(map: Map<String,Any>):RequestBody{
        val json = Gson().toJson(map)
        return RequestBody.create("application/json".toMediaTypeOrNull(),json)
    }

    fun getDateTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }

    fun getYM(time:Long):String{
        return SimpleDateFormat("yyyy-MM").format(time)
    }

    fun getTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }
}